package com.zhuozhou.jdyc.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;

import androidx.annotation.ColorRes;
import androidx.annotation.DrawableRes;
import androidx.annotation.MenuRes;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.ViewModelProvider;

import com.zhuozhou.jdyc.BR;
import com.zhuozhou.jdyc.R;
import com.zhuozhou.jdyc.api.AppManager;
import com.zhuozhou.jdyc.api.ApplicationHelper;
import com.zhuozhou.jdyc.api.ConstantsHelper;
import com.zhuozhou.jdyc.api.UserAccountHelper;
import com.zhuozhou.jdyc.bean.base.ToolbarConfig;
import com.zhuozhou.jdyc.databinding.BaseActivityBinding;
import com.zhuozhou.jdyc.main.base.activity.PermissionsActivity;
import com.zhuozhou.jdyc.main.user.activity.LoginActivity;
import com.zhuozhou.jdyc.util.apiUtil.DensityUtil;
import com.zhuozhou.jdyc.util.apiUtil.StringUtil;
import com.zhuozhou.jdyc.util.log.ToastUtils;
import com.zhuozhou.jdyc.util.permission.PermissionsChecker;
import com.zhuozhou.jdyc.util.theme.ThemeUtils;
import com.zhuozhou.jdyc.wight.dialog.CustomProgressDialog;
import com.zhuozhou.jdyc.wight.dialog.LoginDialog;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Create by CherishTang on 2019/8/1
 * describe:BaseActivity封装
 */
public abstract class BaseActivity<VM extends BaseViewModel, VDB extends ViewDataBinding> extends AppCompatActivity implements BaseView, LoginDialog.OnLoginClickListener {
    public Context context;
    Toolbar mToolbar;
    public VM mViewModel;
    protected VDB binding;
    protected Bundle baseBundle;
    protected ToolbarConfig toolbarConfig = new ToolbarConfig();
    protected BaseActivityBinding toolbarBind;
    protected CustomProgressDialog customProgressDialog;
    // 权限检测器
    private PermissionsChecker mPermissionsChecker;

    protected abstract int getLayoutId();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //初始化适配方案
        DensityUtil.setDensity(ApplicationHelper.getInstance(), this, 360);
        super.onCreate(savedInstanceState);
        AppManager.getAppManager().addActivity(this);
        context = this;
        customProgressDialog = new CustomProgressDialog(this);
        createViewModel();
        toolbarConfig.setTitle(setTitleBar());
        if (hasToolBar()) {
            toolbarBind = DataBindingUtil.setContentView(this, R.layout.base_activity);
            toolbarBind.setVariable(BR.context, this);
            toolbarBind.setVariable(BR.toolbarConfig, toolbarConfig);
        } else {
            binding = DataBindingUtil.setContentView(this, getLayoutId());
        }
        setThemeBarAndToolBarColor(R.color.themeColor);
        baseBundle = (getIntent() == null || getIntent().getExtras() == null) ? new Bundle() : getIntent().getExtras();
        initView();
        initData((getIntent() == null || getIntent().getExtras() == null) ? new Bundle() : getIntent().getExtras());
    }

    @Override
    public void setContentView(int layoutResId) {
        if (hasToolBar()) {
            super.setContentView(R.layout.base_activity);
            FrameLayout container = findViewById(R.id.container);
            mToolbar = findViewById(R.id.main_bar);
            binding = DataBindingUtil.inflate(LayoutInflater.from(this), getLayoutId(), container, true);
            mToolbar.setNavigationOnClickListener(v -> finish());
        } else {
            super.setContentView(layoutResId);
        }
    }

    public Toolbar getToolbar() {
        return mToolbar;
    }

    /**
     * 创建viewModel
     */
    public void createViewModel() {
        if (mViewModel == null) {
            Class modelClass;
            Type type = getClass().getGenericSuperclass();
            if (type instanceof ParameterizedType) {
                modelClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[0];
            } else {
                //如果没有指定泛型参数，则默认使用BaseViewModel
                modelClass = BaseViewModel.class;
            }
            mViewModel = (VM) new ViewModelProvider(this).get(modelClass);
            mViewModel.setBaseView(createBaseView());
        }
    }

    /**
     * 给toolbar添加菜单
     *
     * @param menuRes
     * @param listener
     */
    protected void addMenu(@MenuRes int menuRes, Toolbar.OnMenuItemClickListener listener) {
        if (toolbarBind == null) {
            return;
        }
        toolbarBind.mainBar.inflateMenu(menuRes);
        toolbarBind.mainBar.setOnMenuItemClickListener(listener);
    }

    protected BaseView createBaseView() {
        return this;
    }

    public boolean lacksPermissions(String... permission) {
        return getPermissionsChecker().lacksPermissions(permission);
    }

    private PermissionsChecker getPermissionsChecker() {
        if (mPermissionsChecker == null) {
            mPermissionsChecker = new PermissionsChecker(this);
        }
        return mPermissionsChecker;
    }

    public VDB getBinding() {
        return binding;
    }

    /**
     * 设置toolbar背景色和状态栏的颜色，兼容华为小米手机
     *
     * @param color
     */
    public void setThemeBarAndToolBarColor(@ColorRes int color) {
        try {
            ThemeUtils.setStatusBarLightMode(this, ContextCompat.getColor(this, color));
            toolbarConfig.setBgColor(color);
            ThemeUtils.setStatusBarLightMode(BaseActivity.this, ContextCompat.getColor(BaseActivity.this, color));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置toolbar背景色和状态栏的颜色，兼容华为小米手机
     *
     * @param color
     */
    public void setThemeBarAndToolBarColor(@ColorRes int color, @DrawableRes int backRes) {
        try {
            ThemeUtils.setStatusBarLightMode(this, ContextCompat.getColor(this, color));
            toolbarConfig.setBgColor(color);
            ThemeUtils.setStatusBarLightMode(BaseActivity.this, ContextCompat.getColor(BaseActivity.this, color));
            toolbarConfig.setBackIconRes(backRes);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 权限请求
     *
     * @param requestCode 请求吗
     * @param permissions 权限
     */
    public void requestPermission(int requestCode, String[] permissions) {
        // 缺少权限时, 进入权限配置页面
        if (lacksPermissions(permissions)) {
            PermissionsActivity.startActivityForResult(this, requestCode, permissions);
        }
    }

    public long lastClick = 0;

    /**
     * [防止快速点击]
     *
     * @return false --> 快读点击
     */
    public boolean fastClick(long intervalTime) {
        if (System.currentTimeMillis() - lastClick <= intervalTime) {
            return true;
        }
        lastClick = System.currentTimeMillis();
        return false;
    }

    protected boolean hasToolBar() {
        return true;
    }

    public abstract String setTitleBar();

    /**
     * 初始化布局
     */
    public abstract void initView();

    /**
     * 设置数据
     */
    public abstract void initData(Bundle bundle);


    @Override
    protected void onDestroy() {
        super.onDestroy();
        customProgressDialog.dismiss();
        AppManager.getAppManager().finishActivity(this);
//        try {
//            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//            if (imm != null) {
//                imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(),
//                        0);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            LogUtil.show("软键盘收起异常：" + e);
//        }
    }

    /**
     * 弹出登录dialog
     *
     * @param context     内容
     * @param message     dialog提示内容
     * @param requestCode 登录请求code
     */
    public void showLoginDialog(Activity context, LoginDialog.OnLoginClickListener listener, String message, int requestCode) {
        LoginDialog.getInstance(context)
                .setMessage(message)
                .setCanCancelable(false)
                .setPositiveButton(listener, requestCode)
                .show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (mViewModel != null) {
            mViewModel.onActivityResult(requestCode, resultCode, data);
        }
        if (resultCode == ConstantsHelper.REQUEST_ERROR_LOGIN) {//登陆后重新加载数据
            initData(baseBundle);
        }
    }

    @Override
    public void onLoginClick(View v, int code) {
        LoginActivity.show(this, new Bundle(), code);
    }

    private void closeLoadingDialog() {
        customProgressDialog.getInstance(this).hide();
    }

    private void showLoadingDialog(String dialogMessage, boolean isCanCancel) {
        customProgressDialog.getInstance(this)
                .setCanCancel(isCanCancel)
                .isShowBg(StringUtil.isEmpty(dialogMessage))
                .setMessage(dialogMessage)
                .builder()
                .show();
    }

    @Override
    public void showLoading(String dialogMessage) {
        runOnUiThread(() -> showLoadingDialog(dialogMessage, false));
    }

    @Override
    public void refreshLoading(String dialogMessage) {
        runOnUiThread(() -> customProgressDialog.getInstance(this)
                .setMessage(dialogMessage)
                .builder()
                .show());
    }

    @Override
    public void hideLoading() {
        runOnUiThread(this::closeLoadingDialog);
    }

    @Override
    public void showToast(String msg) {
        runOnUiThread(() -> {
            if (StringUtil.isEmpty(msg)) {
                return;
            }
            ToastUtils.showShort(this, msg);
        });
    }

    @Override
    public void onErrorCode(BaseModelEntity model) {
        if (model != null && (UserAccountHelper.isLoginPast(model.getCode()) || UserAccountHelper.isNoPermission(model.getCode()))) {
            LoginActivity.show(this, new Bundle());
        }
    }

    public void startActivity(Class<?> clx) {
        startActivity(new Intent(this, clx));
    }

    public void startActivity(Class<?> clx, Bundle bundle) {
        Intent intent = new Intent(this, clx);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    public void startActivityForResult(Class<?> clx, int requestCode) {
        startActivityForResult(new Intent(this, clx), requestCode);
    }

    public void startActivityForResult(Class<?> clx, Bundle bundle, int requestCode) {
        Intent intent = new Intent(this, clx);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }
}
